package com.disruptor.base;

import java.nio.ByteBuffer;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.lmax.disruptor.EventHandler;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

//主程序,test
public class LongEventMain {

    public static void main(String[] args) {
        //创建缓冲池
        ExecutorService executor = Executors.newCachedThreadPool();
        //创建event工厂
        LongEventFactory factory = new LongEventFactory();
        //创建ringBuffer大小,最好是2的n次方
        final int ringBufferSize = 1024 * 1024;
        //创建disruptor: ProducerType.SINGLE单生产者     MULTI :多生产者  YieldingWaitStrategy:等待策略
        Disruptor<LongEvent> disruptor =
                new Disruptor<LongEvent>(factory, ringBufferSize, executor, ProducerType.SINGLE, new YieldingWaitStrategy());
        // 连接消费事件方法,多消费者
        EventHandler[] arr = new EventHandler[]{new LongEventHandler01(), new LongEventHandler02()};
        disruptor.handleEventsWith(arr);
        //依赖关系,02先接受,01再接受
        //disruptor.handleEventsWith(new LongEventHandler02()).then(new LongEventHandler01());
        // 启动
        disruptor.start();
        //发布事件
        RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();
        //单生产者,多生产者需要多个生产者对象,同时构造器SINGLE需要改成  MULTI
        //LongEventProducer producer = new LongEventProducer(ringBuffer);
        LongEventProducerWithTranslator producer = new LongEventProducerWithTranslator(ringBuffer);
        ByteBuffer byteBuffer = ByteBuffer.allocate(8);
        for (long l = 0; l < 10; l++) {
            byteBuffer.putLong(l);
            byteBuffer.flip();
            producer.onData(byteBuffer);
        }
        disruptor.shutdown();//关闭 disruptor，方法会堵塞，直至所有的事件都得到处理；
        executor.shutdown();//关闭 disruptor 使用的线程池；如果需要的话，必须手动关闭， disruptor 在 shutdown 时不会自动关闭；
    }

}
